package com.it.mapper;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;

import java.util.*;

@Repository
public class UserMapper {

	private final Map<String, UserDetails> APPLICATION_USERS;

	public UserMapper(PasswordEncoder passwordEncoder) {
		APPLICATION_USERS = new HashMap<>();
		Set<SimpleGrantedAuthority> role = Collections.singleton(new SimpleGrantedAuthority("ROLE_USER"));
		User user1 = new User("123@qq.com", passwordEncoder.encode("123456"), role);
		User user2 = new User("admin", passwordEncoder.encode("123asd"), role);
		APPLICATION_USERS.put(user1.getUsername(), user1);
		APPLICATION_USERS.put(user2.getUsername(), user2);
	}

	public UserDetails findUserByEmail(String email) {
		return Optional.ofNullable(APPLICATION_USERS.get(email))
				.orElseThrow(() -> new UsernameNotFoundException("No user was found"));
	}
}
